//@author A0099566H
package logic;

import storage.ScheduleEvent;
import storage.Storage;
import storage.UndoRedoStackEntry;

public class ScheduleDeleter {
	private Storage eventsList;
	
	private static final String DELETE_COMMAND = "del";
	private static final String ERROR_MSG_INVALID_INDEX = "You have input an Invalid Index! Please Re-try!";
	
	public ScheduleDeleter(Storage eventsList){
		this.eventsList = eventsList;
	}
	
	public String deleteEvent(String indexToBeDeleted){
		if (indexToBeDeleted.length() > 9) return (ERROR_MSG_INVALID_INDEX); //Index shouldn't be more than 9 digits long
		int index = getNumberFromString(indexToBeDeleted);
		if (index > eventsList.getSize() || index <= 0) {
			return (ERROR_MSG_INVALID_INDEX);
		} else {
			ScheduleEvent eventToBeDeleted = eventsList.getEvent(index-1);
			eventsList.getUndoStack().push(new UndoRedoStackEntry(DELETE_COMMAND, eventToBeDeleted));
			eventsList.clearRedoStack();
			return eventsList.deleteEvent(index);
		}
	}
	
	private int getNumberFromString(String indexToBeDeleted) {
		for (int i = 0; i < indexToBeDeleted.length(); i++) {
			if (!isInteger(indexToBeDeleted.charAt(i))) return -1;
		}
		return Integer.parseInt(indexToBeDeleted);
	}

	private boolean isInteger(char charAtIndex) {
		int charInIntegerForm = (int)charAtIndex;
		if (charInIntegerForm <= 57 && charInIntegerForm >= 48) return true;
		return false;
	}

	public String clearEvents() {
		String responseMessage = eventsList.clearAllEvents();
		eventsList.clearRedoStack();
		return responseMessage;
	}
}
